<template>
  <el-dialog :visible.sync="visible" :before-close="beforeClose" title="保存分类">
    <el-form :model="form" label-width="80px">
      <el-form-item label="分类名称" >
        <el-input v-model="form.text" />
      </el-form-item>
      <el-form-item label="分类code" >
        <el-input v-model="form.code" />
      </el-form-item>
      <el-form-item label="父级code" >
        <el-input v-model="form.parentCode" readonly/>
      </el-form-item>
      <el-form-item label="上传图标" >
        <el-upload
          :show-file-list="false"
          :on-success="uploadSuccess"
          class="avatar-uploader"
          action="/api/file/upload">
          <img v-if="form.iconPath" :src="form.iconPath" class="avatar">
          <i v-else class="el-icon-plus avatar-uploader-icon"/>
        </el-upload>
      </el-form-item>
    </el-form>
    <div slot="footer" class="dialog-footer">
      <el-button @click="cancel">取 消</el-button>
      <el-button type="primary" @click="doSubmit">确 定</el-button>
    </div>
  </el-dialog>
</template>

<script>
import { save } from '@/api/JStudy'

export default {
  name: 'SaveJstudy',
  props: {
    jstudyInfo: {
      type: Object,
      default: function() {
        return {}
      }
    },
    visible: {
      type: Boolean,
      default: false
    }
  },
  data() {
    return {
      form: {
        iconPath: null
      }
    }
  },
  watch: {
    visible(nVal) {
      if (nVal) {
        this.form = this.jstudyInfo
      }
      this.$emit('update:visible', nVal)
    }
  },
  methods: {
    beforeClose() {
      this.$emit('update:visible', false)
    },
    cancel() {
      this.$emit('update:visible', false)
    },
    uploadSuccess(res) {
      if (res.code === 200) {
        const data = res.data
        this.form.iconPath = data.smallPath
      }
    },
    doSubmit() {
      const loading = this.$loading(this.loadStudy)
      save(this.form).then(res => {
        this.$notify({
          title: '成功',
          message: '操作成功',
          type: 'success'
        })
        loading.close()
        this.$emit('update:visible', false)
        this.$parent.query()
      }).catch(e => {
        loading.close()
      })
    }
  }
}
</script>

<style scoped>
  .avatar-uploader .el-upload {
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
  }
  .avatar-uploader .el-upload:hover {
    border-color: #409EFF;
  }
  .avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 178px;
    height: 178px;
    line-height: 178px;
    text-align: center;
    border: 1px solid #e4e4e4;
    border-radius: 4px;
  }
  .avatar {
    width: 178px;
    height: 178px;
    display: block;
  }
</style>
